﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NP.BPMReportPlatform.BPMPlatform;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.BPM_Business;
using NP.BPMReportPlatform.Entities.BPM_Platform;
using NP.BPMReportPlatform.Finance.Dto;
using NP.BPMReportPlatform.Utils;
using SqlSugar;
using Volo.Abp.Application.Dtos;

namespace NP.BPMReportPlatform.Finance
{
    public class TransferFixService : BPMReportPlatformAppService, ITransferFixService
    {
        readonly SqlSugarClient _db;
        readonly SqlSugarClient _dbPlatform;
        readonly IBPMUtilsAppService _bPMUtilsApp;
        readonly IBPMPlatformAppService _iBPMPlatformApp;
        public TransferFixService(ISqlSugarAppService sqlSugarAppService, IBPMUtilsAppService bPMUtilsApp, IBPMPlatformAppService iBPMPlatformApp)
        {
            _db = sqlSugarAppService.GetBusinessInstance();
            _dbPlatform = sqlSugarAppService.GetPlatformInstance();
            _bPMUtilsApp = bPMUtilsApp;
            _iBPMPlatformApp = iBPMPlatformApp;
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<List<TransferFixOutput>> ExportAsync(GetTransferFixInput input)
        {

            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToListAsync();
            return listViewDto;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<TransferFixOutput>> GetAllAsync(GetTransferFixInput input)
        {
            RefAsync<int> totalCount = 0;

            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);

            listViewDto.ForEach(x => x.Url = _bPMUtilsApp.GetProcessUrl(x.InstanceId, userId));

            return new PagedResultDto<TransferFixOutput>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };

        }


        private ISugarQueryable<TransferFixOutput> GetQueryable(GetTransferFixInput input)
        {
            var SubmitDateEnd = DateTime.Now;
            var SubmitDateStrat= DateTime.Now;
            var FinishTimeStart= DateTime.Now;
            var FinishTimeEnd = DateTime.Now;
            if (input.SubmitDate.HasValue)
            {
                SubmitDateStrat = input.SubmitDate.Value;
                SubmitDateEnd = input.SubmitDate.Value.AddDays(1);
            }
            if (input.ApprovalDate.HasValue)
            {
                FinishTimeStart = input.ApprovalDate.Value;
                FinishTimeEnd = input.ApprovalDate.Value.AddDays(1);
            }
            var noList = new List<string>();
            if (!string.IsNullOrEmpty(input.TransferFixNo))
            {
                noList = input.TransferFixNo.Split(new char[] { ',', ' ','\n' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            }


            var uQuery = _dbPlatform.Queryable<Users>()
                .WhereIF(!string.IsNullOrEmpty(input.Applicat), x => x.UserName.Contains(input.Applicat) || x.WorkNumber== input.Applicat).AS("BPM_Platform.Users");
            var pQuery = _db.Queryable<BusinessProcessesNew>()
                .WhereIF(input.SubmitDate.HasValue,x=>x.StartTime>= SubmitDateStrat && x.StartTime < SubmitDateEnd)
                .WhereIF(input.ApprovalDate.HasValue, x => x.FinishTime >= FinishTimeStart && x.FinishTime < FinishTimeEnd);
            var tQuery = _db.Queryable<TransferFixHeader>()
                .WhereIF(!string.IsNullOrEmpty(input.TransferFixNo), x => noList.Contains(x.InstanceNumber))
                .WhereIF(!string.IsNullOrEmpty(input.TransferFixName),x=>x.TransferFixName.Contains(input.TransferFixName))
                .WhereIF(!string.IsNullOrEmpty(input.FactoryCode), x => x.TransferFixFactory == input.FactoryCode);


            var query = pQuery.InnerJoin(uQuery, (p, u) => p.StartUserId == u.UserId)
                    .InnerJoin(tQuery, (p, u, t) => p.InstanceId == t.InstanceNumber)
                    .Select((p, u, t) => new TransferFixOutput()
                    {
                        InstanceId = p.InstanceId,
                        CreateDate = p.StartTime,
                        StartUserName = p.StartUserName,
                        StatusName = p.ProcessStatusName,
                        Title = t.TransferFixName,
                    }).OrderBy(p => p.InstanceId, OrderByType.Desc);


            return query;
        }


    }
}
